/**
 * 工具类
 */
import * as CryptoTS from 'crypto-ts';
import MD5 from '@/libs/MD5';

/**
 * 获取cookie内容
 * @param name cookie名
 */
export const GetCookie = (name: string): string | null => {
   name = name + "=";
   let start = document.cookie.indexOf(name), value = null;
   if (start > -1) {
      let end = document.cookie.indexOf("; ", start);
      if (end == -1) {
         end = document.cookie.length;
      }
      value = document.cookie.substring(start + name.length, end);
   }
   return value;
};

/**
 * 获取storage的值
 * @param key key名
 */
export const GetSession = (key: string): string | null => {
   try {
      const s = sessionStorage.getItem(key);
      if (!(typeof s === 'string') || s === '') {
         return null
      }

      return s
   } catch (e) {
      return null
   }
};

/**
 * 解密字符串
 */
export const Decrypt3Des=function(str:string, key:string, iv:string) {
   let crypto_key = CryptoTS.enc.Utf8.parse(new MD5().hex_md5(key).toUpperCase());
   let crypto_iv = CryptoTS.enc.Utf8.parse(new MD5().hex_md5(iv).toUpperCase());
   let crypto_str = CryptoTS.enc.Utf8.parse(str).toString(CryptoTS.enc.Utf8);
   let decrypt_str = CryptoTS.AES.decrypt(
       crypto_str,
       crypto_key,
       {
          iv: crypto_iv,
          mode: CryptoTS.mode.CBC,
          padding: CryptoTS.pad.PKCS7,
       }
   );
   return decrypt_str.toString(CryptoTS.enc.Utf8);
};

/**
 * 加密字符串
 */
export const Encrypt3Des=function(str:string, key:string, iv:string) {
   let crypto_key = CryptoTS.enc.Utf8.parse(new MD5().hex_md5(key).toUpperCase());
   let crypto_iv = CryptoTS.enc.Utf8.parse(new MD5().hex_md5(iv).toUpperCase());
   let crypto_str = CryptoTS.enc.Utf8.parse(str).toString(CryptoTS.enc.Utf8);
   let encode_str = CryptoTS.AES.encrypt(
       crypto_str,
       crypto_key,
       {
          iv: crypto_iv,
           mode: CryptoTS.mode.CBC,
           padding: CryptoTS.pad.PKCS7,

       }
   );
   return CryptoTS.enc.Utf8.stringify(CryptoTS.enc.Utf8.parse(encode_str.toString()));
};


